package com.sun.designpatternsdemo.flyweight

import android.os.Bundle
import com.sun.designpatternsdemo.R
import com.sun.designpatternsdemo.app.AppConstant
import com.sun.designpatternsdemo.app.EMTagHandler
import com.sun.designpatternsdemo.base.BaseActivity
import com.sun.designpatternsdemo.databinding.ActivityFlyWeightBinding
import com.sun.designpatternsdemo.flyweight.bean.Circle
import com.sun.designpatternsdemo.flyweight.bean.ShapeFactory

/**
 * 享元模式（Flyweight Pattern）
 * 主要用于减少创建对象的数量，以减少内存占用和提高性能。
 * 这种类型的设计模式属于结构型模式，它提供了减少对象数量从而改善应用所需的对象结构的方式。
 */
class FlyWeightActivity : BaseActivity<ActivityFlyWeightBinding>() {
    private val colors = arrayOf("Red", "Blue", "Yellow", "White", "Black")

    override fun layoutId(): Int = R.layout.activity_fly_weight

    override fun initView(savedInstanceState: Bundle?) {
        title = "享元模式"
        mDataBind.apply {
            tvDefine.text = EMTagHandler.fromHtml(AppConstant.FLYWEIGHT_DEFINE)
            btGetCircle.setOnClickListener {
                for (i in 0..20) {
                    val circle: Circle = ShapeFactory.getShape(getRandomColor()) as Circle
                    circle.apply {
                        x = getRandomX()
                        y = getRandomY()
                        radius = 100
                        draw()
                    }
                }
            }
        }
    }

    /**
     * 0.0-1.0  * [1-6]
     */
    private fun getRandomColor(): String {
        return colors[(Math.random() * colors.size).toInt()]
    }

    private fun getRandomX(): Int = (Math.random() * 100).toInt()

    private fun getRandomY(): Int = (Math.random() * 100).toInt()
}